package com.doremi.presentation.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.doremi.R;
import com.doremi.service.play_songs.PlaySongsServiceAcces;
import com.doremi.service.play_songs.TrackQueque;
import com.doremi.util.Track;

/*
 * clase que permite listar los track,
 * y al cliquear en el boton "+"
 * los agrega a una lista de reproduccion 
 */
public class TracksToAddArrayAdapter extends ArrayAdapter<String> {

  

  //private final List<String> list;
  private ArrayList<Track> trackList;

  private final Activity activity;

  
  public TracksToAddArrayAdapter(Activity activity, List<String> list,ArrayList<Track> trackList) {
    super(activity, R.layout.track_to_add_row_layout, list);
    this.activity = activity;
    //this.list = list;
    this.trackList=trackList;
  }

  static class ViewHolder {
    protected TextView addTrackTextView;
    protected Button addTrackButton;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    if (convertView == null) {
      LayoutInflater inflator = activity.getLayoutInflater();
      view = inflator.inflate(R.layout.track_to_add_row_layout, null);
      
      ViewHolder viewHolder=new ViewHolder();
      viewHolder.addTrackTextView=(TextView) view.findViewById(R.id.addTrackTextView);
      viewHolder.addTrackButton=(Button) view.findViewById(R.id.addTrackButton);
      
      view.setTag(viewHolder);
      //se le agrega un tag al button con el track asociado
      viewHolder.addTrackButton.setTag(trackList.get(position));
      
      //seteo el evento que permite agregarlos a la lista de reproduccion
      viewHolder.addTrackButton.setOnClickListener(new View.OnClickListener() {
		
		public void onClick(View v) {
			Button addTrackButton=(Button)v;
			Track track=(Track)addTrackButton.getTag();
			Log.v("track to add:",track.getName());
			//obtengo la instancia de la cola de reproduccion (singleton)
			TrackQueque trackQueque=TrackQueque.instance();
			trackQueque.add(track,activity);
			PlaySongsServiceAcces.addSongService(activity);
			
		}
	});
    }
    else{ //este else es util para listas muy largas , ahorra memoria (cuidado)
      view = convertView;
      //se le agrega un tag al button con el track asociado
      ((ViewHolder) view.getTag()).addTrackButton.setTag(trackList.get(position));
    }
    //
    ViewHolder holder = (ViewHolder) view.getTag();
    holder.addTrackTextView.setText((trackList.get(position)).getName());
    
    return view;
  }
} 